package com.zhang.hadoop.netty.nio.channel;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author: zhang yufei
 * @create: 2022-01-09 15:48
 * @description: 本地文件写入
 **/
public class NIOFileChannel01 {

    public static void main(String argsp[]) {
        try {
            String str = "hello";
            //创建一个输出流 channel
            FileOutputStream fileOutputStream = new FileOutputStream("C:\\zhang\\workspace\\data\\nio\\file01.txt");
            //通过fileOutputStream 获取对应的FileChannel
            //这个fileChannel 真是类型是FileChannelImpl
            FileChannel fileChannel = fileOutputStream.getChannel();
            //创建一个缓冲区 ByteBuffer
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            //将str放入byteBuffer
            byteBuffer.put(str.getBytes());
            //对byteBuffer进行flip
            byteBuffer.flip();
            //将byteBuffer数据吸入到fileChannel
            fileChannel.write(byteBuffer);
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
